<?php
	function get_connection($hostname, $userid, $passwd){
		$connection = mysqli_connect($hostname, $userid, $passwd);
		if(mysqli_connect_errno($connection)){
			echo "unable to connect to test data base";
			exit("unable to connect to test data base");
		}else{
			return $connection;
		}
	}
	function execute_query($connection, $query, $error_msg){
		if(!mysqli_query($connection, $query)){
			echo $error_msg.mysqli_error($connection);
			exit($error_msg.mysqli_error($connection));
		}
	}
	function create_db($connection, $dbname){
		$creat_db_query = "CREATE DATABASE ".$dbname;
		execute_query($connection, $creat_db_query, "unable to create db");
	}
	function change_db($connection,$dbname){
		$change_db_query = "use ".$dbname;
		execute_query($connection, $change_db_query, "unable to change db");
	}
	function create_tables($connection){
		$create_user_credentials = "create table user_credentials ( id int not null auto_increment, user_name char(20) not null, password char(40), primary key(id), unique key(user_name))";
		$create_user_profile = "create table user_profile ( id int not null auto_increment, user_id int not null references user_credentials(id), user_firstname char(20),user_lastname char(20), mobile_number char(10), email_id char(50), primary key(id))";
		execute_query($connection, $create_user_credentials, "unable to create user credentials table");
		execute_query($connection, $create_user_profile, "unable to create user profile table");
	}
	function save_config($hostname, $userid, $passwd, $dbname){
		$file = fopen("config.txt","a+") or exit("Sorry not able to save the detail");
		fputs($file, $hostname.":");
		fputs($file, $userid.":");
		fputs($file, $passwd.":");
		fputs($file, $dbname);
		fputs($file,"\n");
		fclose($file);
	}
	if(!empty($_POST["submit"])){
		$connection = get_connection($_POST["hostname"], $_POST["userid"], $_POST["passwd"]);
		//STEP : 1
		create_db($connection, $_POST["dbname"]);
		//STEP : 2
		change_db($connection, $_POST["dbname"]);
		//STEP : 3
		create_tables($connection);
		//STEP : 4
		mysqli_close($connection);
		save_config($_POST["hostname"], $_POST["userid"], $_POST["passwd"], $_POST["dbname"]);
		header("Location: index.php?install=success");
		exit();
	}	
?>
<!DOCTYPE html>
<head>
<title>Intallation Page</title>
</head>
<body>
	<h1>Welcome to Election Management System</h1>
	<form name="install" method="post" action="install.php">
		<table border='0'>
			<tr>
				<td>Host Name:</td>
				<td><input type="text" name="hostname" required /></td>
			</tr>
			<tr>
				<td>User Name:</td>
				<td><input type="text" name="userid" required /></td>
			</tr>
			<tr>
				<td>Password:</td>
				<td><input type="password" name="passwd" required /></td>
			</tr>
			<tr>
				<td>Database Name:</td>
				<td><input type="text" name="dbname" required /></td>
			</tr>
			<tr align="left">
				<td colspan="2"><input type="submit" name="submit" value="submit" />
				</td>
			</tr>
		</table>
	</form>
</body>